package test.my.com.myapplicationtest.image_container;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import test.my.com.myapplicationtest.R;

/**
 * Created by ThinkPad on 2016/2/17.
 */
public class ImageContainer extends ViewGroup{

    /** 最多容纳图片数量 **/
    public static final int IMAGE_MAX_NUMBER = 9;

    public static final int DEFAULT_IMAGE_SPACE = 10;
    public static final int DEFAULT_SMALL_IMAGE_WIDTH_AND_HEIGHT = 70;
    public static final int DEFAULT_ONE_IMAGE_WIDTH_AND_HEIGHT = 300;
    /** 每张图片间距 **/
    private int mImageSpace;
    /** 当图片多了后，小图宽高 **/
    private int mSmallImageWidth;
    private int mSmallImageHeight;

    // 图片资源数组
    private int[] imagesArray;

    private Context mContext;

    private OnImageClickListener mOnImageClickListener;

    public void setmOnImageClickListener(OnImageClickListener mOnImageClickListener) {
        this.mOnImageClickListener = mOnImageClickListener;
    }

    public ImageContainer(Context context) {
        super(context);
    }

    public ImageContainer(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ImageContainer(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ImageContainer,defStyleAttr,0);
        int n = ta.getIndexCount();
        for(int i = 0;i<n;i++){
            int attr = ta.getIndex(i);
            switch (attr){
                case R.styleable.ImageContainer_mImageSpace:
                    this.mImageSpace = ta.getDimensionPixelOffset(attr,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, DEFAULT_IMAGE_SPACE,
                            getResources().getDisplayMetrics()));
                    break;
                case R.styleable.ImageContainer_mSmallImageWidth:
                    this.mSmallImageWidth = ta.getDimensionPixelOffset(attr,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, DEFAULT_SMALL_IMAGE_WIDTH_AND_HEIGHT,
                            getResources().getDisplayMetrics()));
                    break;
                case R.styleable.ImageContainer_mSmallImageHeight:
                    this.mSmallImageHeight = ta.getDimensionPixelOffset(attr,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, DEFAULT_SMALL_IMAGE_WIDTH_AND_HEIGHT,
                            getResources().getDisplayMetrics()));
                    break;
            }
        }
        ta.recycle();
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // 获得它的父容器为它设置的测量模式和大小
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

        // 容器总宽度
        int vgWidth = 0;
        // 容器总高度
        int vgHeight = 0;

        // 子view总数
        int viewCount = getChildCount();

        if(viewCount == 1){ // 如果只有一张图片图片正常显示
            View oneView = getChildAt(0);
            measureChild(oneView, widthMeasureSpec, heightMeasureSpec);
            vgWidth = oneView.getMeasuredWidth()>DEFAULT_ONE_IMAGE_WIDTH_AND_HEIGHT?DEFAULT_ONE_IMAGE_WIDTH_AND_HEIGHT:oneView.getMeasuredWidth();
            vgHeight = oneView.getMeasuredHeight()>DEFAULT_ONE_IMAGE_WIDTH_AND_HEIGHT?DEFAULT_ONE_IMAGE_WIDTH_AND_HEIGHT:oneView.getMeasuredHeight();
//            vgWidth = oneView.getMeasuredWidth();
//            vgHeight = oneView.getMeasuredHeight();
        }else if(viewCount == 2 || viewCount == 3){ // 如果有两张图片图片正常显示
            for(int i=0;i<viewCount;i++){
                View child = getChildAt(i);

                ContainerLayoutParams clp = (ContainerLayoutParams) child.getLayoutParams();
                clp.cLeft = (i % 3) * (mSmallImageWidth + mImageSpace);
                clp.cTop = 0;

                vgWidth += mSmallImageWidth;
            }
            vgWidth += (viewCount - 1) * mImageSpace;
            vgHeight = mSmallImageHeight;
        }else if(viewCount == 4){   // 如果有4张图片显示
            for(int i=0;i<viewCount;i++){
                View child = getChildAt(i);

                ContainerLayoutParams clp = (ContainerLayoutParams) child.getLayoutParams();
                clp.cLeft = (i % 2) * (mSmallImageWidth + mImageSpace);
                clp.cTop =  (i / 2) * (mSmallImageWidth + mImageSpace);

            }
            vgWidth  = 2 * mSmallImageWidth + mImageSpace;
            vgHeight = 2 *mSmallImageHeight + mImageSpace;
        }else if(viewCount>4){   // 如果有大于4张图片显示
            for(int i=0;i<viewCount;i++){
                View child = getChildAt(i);

                ContainerLayoutParams clp = (ContainerLayoutParams) child.getLayoutParams();
                clp.cLeft = (i % 3) * (mSmallImageWidth + mImageSpace);
                clp.cTop =  (i / 3) * (mSmallImageWidth + mImageSpace);

            }
            vgWidth = sizeWidth;
            vgHeight = ((viewCount-1)/3+1)*mSmallImageHeight + (viewCount-1)/3*mImageSpace;
        }

        setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth
                : vgWidth, (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight
                : vgHeight);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int viewCount = getChildCount();
        if(viewCount == 1){
            View child = getChildAt(0);
            child.layout(0, 0, child.getMeasuredWidth(), child.getMeasuredHeight());
        }else {
            for(int i=0;i<viewCount;i++){
                View child = getChildAt(i);
                ContainerLayoutParams clp = (ContainerLayoutParams) child.getLayoutParams();
                child.layout(clp.cLeft, clp.cTop, clp.cLeft + mSmallImageWidth,
                        clp.cTop + mSmallImageHeight);
            }
        }
    }

    // 设置图片
    public void setImagesArray(int[] imagesArray) {
        this.imagesArray = imagesArray;
        for(int i = 0; i<(imagesArray.length>IMAGE_MAX_NUMBER?IMAGE_MAX_NUMBER:imagesArray.length); i++){
            final int position = i;
            ImageView iv = new ImageView(mContext);
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            iv.setImageResource(imagesArray[i]);
            iv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mOnImageClickListener != null){
                        mOnImageClickListener.imageClick(position);
                    }
                }
            });
            addView(iv);
        }
    }


    @Override
    public android.view.ViewGroup.LayoutParams generateLayoutParams(
            AttributeSet attrs) {
        return new ContainerLayoutParams(getContext(), attrs);
    }

    @Override
    protected android.view.ViewGroup.LayoutParams generateDefaultLayoutParams() {
        return new ContainerLayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
    }

    @Override
    protected android.view.ViewGroup.LayoutParams generateLayoutParams(
            android.view.ViewGroup.LayoutParams p) {
        return new ContainerLayoutParams(p);
    }

    @Override
    protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams p) {
        return p instanceof ContainerLayoutParams;
    }


    public static class ContainerLayoutParams extends ViewGroup.LayoutParams{

        public int cLeft =0;
        public int cTop =0;

        public ContainerLayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
        }

        public ContainerLayoutParams(int width, int height) {
            super(width, height);
        }

        public ContainerLayoutParams(LayoutParams source) {
            super(source);
        }
    }

    interface OnImageClickListener{
        void imageClick(int position);
    }
}
